import jargs.gnu.CmdLineParser;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


/*
A program used to download ESL Podcast learning guides.
 
ESLPOD homepage: http://www.eslpod.com/website/
login form: https://www.eslpod.com/website/amember/login.php
link to guide: https://www.eslpod.com/website/amember/podcast_pdf/ESLPod_690_Guide.pdf
link to a cafe guide: https://www.eslpod.com/website/amember/podcast_pdf/English_Cafe_296_Guide.pdf

modified from http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientFormLogin.java
depends on httpclient-4.1.1, httpcore-4.1, commons-loggin-1.1.1 from Apache's HttpComponents.

ken, 2010.6.21 
*/
public class epdl { //: eslpod downloader
   
   public static void main(String[] args) throws Exception {
      if(args.length<=0) {
         printUsage();
         return;
      }
      final CmdLineParser parser=new CmdLineParser();
      parser.addBooleanOption('c', "cafe");
      parser.addIntegerOption('f', "from");
      
      try {
         parser.parse(args);
      } catch(CmdLineParser.OptionException e) {
         System.err.println(e.getMessage());
         printUsage();
         System.exit(2);
      }
   
      final DefaultHttpClient httpClient=new DefaultHttpClient();
      try {
         // [ login first
         login(httpClient, "https://www.eslpod.com/website/amember/login.php",
               "amember_login", "kuanying", "amember_pass", "2xuijlji");

         // [ get the files
         //getEnglishCafe(httpClient, 298, 33);
         getLearningGuide(httpClient, 696, 164);
      } finally {
         httpClient.getConnectionManager().shutdown();
      } 
   }
   
   private static void printUsage() {
      System.out.print("download episode 696:");
      System.out.println("java epdl [-u, --username USER_NAME] [-p, --password PASSWORD] [-c, --cafe]");
      
      System.out.print("download english cafe espisod 298:");
      System.out.println("java epdl -c 298");
      
      System.out.print("download espisods 164 to 696:");
      System.out.println("java epdl 164 696");
      
      System.out.print("download english cafe espisods 33 to 298:");
      System.out.println("java epdl -c 33 298");
   }

   private static void getLearningGuide(DefaultHttpClient httpClient, int max,
         int min) throws Exception {
      for(int index=max; index >= min; index--) {
         downloadFile(httpClient, 
               "https://www.eslpod.com/website/amember/podcast_pdf/ESLPod_"+index+"_Guide.pdf",
               index+".pdf");
      }
      
   }

   private static void getEnglishCafe(DefaultHttpClient httpClient, int max, int min) throws Exception {
      for(int index=max; index >= min; index--) {
         downloadFile(httpClient, 
               "https://www.eslpod.com/website/amember/podcast_pdf/English_Cafe_"+index+"_Guide.pdf", 
               "cafe"+index+".pdf");
      }
      
   }

   private static void downloadFile(DefaultHttpClient httpClient, String url,
         String filename) throws Exception {
      HttpGet guideHttpGet=new HttpGet(url);

      System.out.println("executing request" + guideHttpGet.getRequestLine());
      HttpResponse guideResponse=httpClient.execute(guideHttpGet);
      HttpEntity guideEntity=guideResponse.getEntity();

      System.out.println("----------------------------------------");
      System.out.println(guideResponse.getStatusLine());
      if(guideEntity != null) {
         System.out.println("Response content length: "
               + guideEntity.getContentLength());

         final File f=new File(filename);
         final FileOutputStream oStream=new FileOutputStream(f);
         guideEntity.writeTo(oStream);
         oStream.close();
         // guideEntity.writeTo(System.out);
      }
      EntityUtils.consume(guideEntity);

   }

   //@url: login url
   //@uvalue: name
   //@pvalue: password
   //@uname: field name for name
   //@pname: field name for password
   public static DefaultHttpClient login(DefaultHttpClient httpclient, String url, String uname, String uvalue, 
                                                     String pname, String pvalue) throws Exception {
      HttpPost httpost=new HttpPost(url);

      List<NameValuePair> nvps=new ArrayList<NameValuePair>();
      nvps.add(new BasicNameValuePair(uname, uvalue));
      nvps.add(new BasicNameValuePair(pname, pvalue));

      httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

      HttpResponse response=httpclient.execute(httpost);
      HttpEntity entity=response.getEntity();

      System.out.println("Login form get: " + response.getStatusLine());
      EntityUtils.consume(entity);

      System.out.println("Post logon cookies:");
      List<Cookie> cookies=httpclient.getCookieStore().getCookies();
      if(cookies.isEmpty()) {
         System.out.println("None");
      } else {
         for(int i=0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
         }
      }
      return httpclient;
   }
}
